from flask import Blueprint, request, jsonify
from app.models import db, Area, User
from app.utils.auth import require_permission, get_current_user
from sqlalchemy.exc import IntegrityError
from datetime import datetime

areas_bp = Blueprint('areas', __name__)

@areas_bp.route('/', methods=['GET'], strict_slashes=False)
@require_permission('area.view')
def get_areas():
    """获取区域列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        search = request.args.get('search', '')
        include_members = request.args.get('include_members', 'false').lower() == 'true'
        
        query = Area.query
        
        # 搜索过滤
        if search:
            query = query.filter(Area.name.contains(search))
        
        # 分页
        if per_page == -1:  # 获取所有数据
            areas = query.filter_by(is_active=True).order_by(Area.name).all()
            total = len(areas)
            
            if include_members:
                areas_data = [area.to_dict_with_members() for area in areas]
            else:
                areas_data = [area.to_dict() for area in areas]
            
            return jsonify({
                'areas': areas_data,
                'total': total,
                'page': 1,
                'per_page': total,
                'pages': 1
            }), 200
        else:
            pagination = query.filter_by(is_active=True).order_by(Area.name).paginate(
                page=page, per_page=per_page, error_out=False
            )
            
            if include_members:
                areas_data = [area.to_dict_with_members() for area in pagination.items]
            else:
                areas_data = [area.to_dict() for area in pagination.items]
            
            return jsonify({
                'areas': areas_data,
                'total': pagination.total,
                'page': pagination.page,
                'per_page': pagination.per_page,
                'pages': pagination.pages
            }), 200
            
    except Exception as e:
        return jsonify({'error': f'获取区域列表失败: {str(e)}'}), 500

@areas_bp.route('/<int:area_id>', methods=['GET'])
@require_permission('area.view')
def get_area(area_id):
    """获取单个区域详情"""
    try:
        area = Area.query.get_or_404(area_id)
        include_members = request.args.get('include_members', 'true').lower() == 'true'
        
        if include_members:
            return jsonify(area.to_dict_with_members()), 200
        else:
            return jsonify(area.to_dict()), 200
            
    except Exception as e:
        return jsonify({'error': f'获取区域详情失败: {str(e)}'}), 500

@areas_bp.route('/options', methods=['GET'])
@require_permission('area.view')
def get_area_options():
    """获取区域选项列表（用于下拉选择）"""
    try:
        areas = Area.query.filter_by(is_active=True).order_by(Area.name).all()
        options = [{'value': area.id, 'label': area.name} for area in areas]
        return jsonify(options), 200
    except Exception as e:
        return jsonify({'error': f'获取区域选项失败: {str(e)}'}), 500

@areas_bp.route('/', methods=['POST'])
@require_permission('area.create')
def create_area():
    """创建新区域"""
    try:
        data = request.get_json()
        
        # 验证必填字段
        if not data.get('name'):
            return jsonify({'error': '区域名称不能为空'}), 400
        
        # 检查区域名称是否已存在
        existing_area = Area.query.filter_by(name=data['name']).first()
        if existing_area:
            return jsonify({'error': '区域名称已存在'}), 400
        
        # 验证组长是否存在
        leader_id = data.get('leader_id')
        if leader_id:
            leader = User.query.get(leader_id)
            if not leader:
                return jsonify({'error': '指定的组长不存在'}), 400
        
        # 创建区域
        area = Area(
            name=data['name'],
            leader_id=leader_id,
            description=data.get('description', ''),
            is_active=data.get('is_active', True)
        )
        
        db.session.add(area)
        db.session.commit()
        
        return jsonify({
            'message': '区域创建成功',
            'area': area.to_dict()
        }), 201
        
    except IntegrityError:
        db.session.rollback()
        return jsonify({'error': '区域名称已存在'}), 400
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'创建区域失败: {str(e)}'}), 500

@areas_bp.route('/<int:area_id>', methods=['PUT'])
@require_permission('area.edit')
def update_area(area_id):
    """更新区域信息"""
    try:
        area = Area.query.get_or_404(area_id)
        data = request.get_json()
        
        # 验证必填字段
        if not data.get('name'):
            return jsonify({'error': '区域名称不能为空'}), 400
        
        # 检查区域名称是否已存在（排除当前区域）
        existing_area = Area.query.filter(
            Area.name == data['name'],
            Area.id != area_id
        ).first()
        if existing_area:
            return jsonify({'error': '区域名称已存在'}), 400
        
        # 验证组长是否存在
        leader_id = data.get('leader_id')
        if leader_id:
            leader = User.query.get(leader_id)
            if not leader:
                return jsonify({'error': '指定的组长不存在'}), 400
        
        # 更新区域信息
        old_name = area.name
        area.name = data['name']
        area.leader_id = leader_id
        area.description = data.get('description', '')
        area.is_active = data.get('is_active', True)
        area.updated_at = datetime.utcnow()
        

        
        db.session.commit()
        
        return jsonify({
            'message': '区域更新成功',
            'area': area.to_dict()
        }), 200
        
    except IntegrityError:
        db.session.rollback()
        return jsonify({'error': '区域名称已存在'}), 400
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'更新区域失败: {str(e)}'}), 500

@areas_bp.route('/<int:area_id>', methods=['DELETE'])
@require_permission('area.delete')
def delete_area(area_id):
    """删除区域（软删除）"""
    try:
        area = Area.query.get_or_404(area_id)
        
        # 检查是否有用户关联到此区域
        if area.members:
            return jsonify({'error': '无法删除，因为仍有用户属于该区域'}), 400
        
        # 软删除
        area.is_active = False
        area.updated_at = datetime.utcnow()
        
        db.session.commit()
        
        return jsonify({'message': '区域删除成功'}), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'删除区域失败: {str(e)}'}), 500

@areas_bp.route('/<int:area_id>/members', methods=['GET'])
@require_permission('area.view')
def get_area_members(area_id):
    """获取区域成员列表"""
    try:
        area = Area.query.get_or_404(area_id)
        members = area.get_members()
        
        members_data = [{
            'id': member.id,
            'name': member.name,
            'username': member.username,
            'employee_id': member.employee_id,
            'position': member.position,
            'department': member.department,
            'phone': member.phone,
            'email': member.email,
            'role': member.role,
            'is_active': member.is_active
        } for member in members]
        
        return jsonify({
            'area': area.to_dict(),
            'members': members_data,
            'total': len(members_data)
        }), 200
        
    except Exception as e:
        return jsonify({'error': f'获取区域成员失败: {str(e)}'}), 500